package main

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"strings"
)

func test2() {
	conn, dialErr := net.Dial("tcp", "localhost:5500")
	if dialErr != nil {
		fmt.Println("connect error", dialErr.Error())
		return
	}

	// 从键盘中读取数据
	inputReader := bufio.NewReader(os.Stdin)
	fmt.Println("what is your name")
	name, readErr := inputReader.ReadString('\n')
	if readErr != nil {
		fmt.Println("read string error", readErr.Error())
		return
	}
	sendName := strings.Trim(name, "\r\n")
	// 给服务端发送消息
	for {
		fmt.Println("send something! Q to quit")
		input, err := inputReader.ReadString('\n')
		if err != nil {
			fmt.Println("read string error", err.Error())
			return
		}
		sendMessage := strings.Trim(input, "\r\n")
		if sendMessage == "Q" {
			return
		}
		_, writeErr := conn.Write([]byte(sendName + " says: " + sendMessage))
		if writeErr != nil {
			fmt.Println("write error", err.Error())
			return
		}
	}
}

func test3() {
	urls := []string{
		"https://www.baidu.com",
		"https://www.google.com",
		"https://www.golang.com",
	}

	for _, url := range urls {
		resp, err := http.Head(url)
		if err != nil {
			fmt.Println("head error", err.Error())
			return
		}
		fmt.Println(resp.Status)
	}
}

func checkError(err error) {
	if err != nil {
		fmt.Println("get error", err.Error())
		return
	}
}

func test4() {
	res, err := http.Get("https://google.com")
	checkError(err)
	data, err := io.ReadAll(res.Body)
	checkError(err)
	fmt.Println(string(data))
}

func simpleServer(rsp http.ResponseWriter, req *http.Request) {
	_, err := io.WriteString(rsp, "<h1>hello, world</h1>")
	checkError(err)
}

func formServer(rsp http.ResponseWriter, req *http.Request) {
	const form = `
	<html><body>
		<form action="#" method="post" name="bar">
			<input type="text" name="in" />
			<input type="submit" value="submit"/>
		</form>
	</body></html>
	`
	rsp.Header().Set("Content-Type", "text/html")
	switch req.Method {
	case "GET":
		_, err := io.WriteString(rsp, form)
		checkError(err)
	case "POST":
		fmt.Println("post req: ", req.FormValue("in"))
		_, err := io.WriteString(rsp, req.FormValue("in"))
		checkError(err)
	}
}

func test5() {
	http.HandleFunc("/test1", simpleServer)
	http.HandleFunc("/test2", formServer)
	err := http.ListenAndServe("localhost:8080", nil)
	checkError(err)
}

func main() {
	test5()
}
